import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, LogOutRemoveAll } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 5000
})

// 如果不适用全局响应，特定处理某几个接口，则创建一个新的实例
// export const service2 = axios.create({
//   baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
//   timeout: 5000
// })

service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.error_no === 402) {
      MessageBox.confirm('你已经退出了，请重新登录', '确认退出', {
        confirmButtonText: '重新登录',
        // cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        LogOutRemoveAll()
        location.reload()
      })
      return null
    }
    if (res.error_no !== 200) {
      Message({
        message: res.error_msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.error_msg || 'Error'))
    } else {
      return res.result
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

// 针对于数据进行再次封装，例如可以写日志等操作
export function request(obj, config = undefined) {
  return service.request(obj)
}

